<?php
/**
 * @author CptSoap
 * @email 694652150@qq.com
 * @date 2021年9月27日
 * 桶内对象的增删改查
 */

namespace app\admin\utils;

use Qcloud;

class cosOper
{
    const secretId = "AKIDVlAOOCm9IG1YrvkJdhW5QZTBfwzoPnzx"; //"云 API 密钥 SecretId";
    const secretKey = "mIYcQ1PYT9ZkfKkwufATaU9bnjPp0va0"; //"云 API 密钥 SecretKey";
    const region = "ap-guangzhou"; //设置一个默认的存储桶地域

    const bucket = 'php-mall-1255644734';


    private $cosClient;

    public function __construct()
    {
        $this->cosClient = new Qcloud\Cos\Client(
            array(
                'region' => self::region,
                'credentials' => array(
                    'secretId' => self::secretId,
                    'secretKey' => self::secretKey)
            )
        );
    }

    /**
     * 上传一个文件到桶中。给定文件的绝对路径和桶中的Key值。
     * @param $srcPath
     * @param $key
     * @param string $bucket
     * @return false|object
     * @author CptSoap
     * @date 2021/9/27
     */
    public function uploadObj($srcPath, $key, string $bucket = self::bucket)
    {
        try {
            $file = fopen($srcPath, "rb");
            if ($file) {
                $result = $this->cosClient->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file));
                ontimeLog::mylog("COS上传成功：" . $result, __FILE__, __METHOD__);
                return $result;
            }
        } catch (\Exception $e) {
            ontimeLog::mylog("COS上传失败：" . $e, __FILE__, __METHOD__);
            return false;
        }
        return false;
    }

    /**
     * 删除桶中的一个文件。给定桶中的Key值。
     * @param $key
     * @param string $bucket
     * @return bool
     * @author CptSoap
     * @date 2021/9/27
     */
    public function deleteObj($key, string $bucket = self::bucket): bool
    {
        try {
            $result = $this->cosClient->deleteObject(array(
                'Bucket' => $bucket,
                'Key' => $key,
                'VersionId' => 'string'
            ));
            ontimeLog::mylog($result, __FILE__, __METHOD__);
            return true;
        } catch (\Exception $e) {
            // 请求失败
            ontimeLog::mylog("cos删除失败：" . $e, __FILE__, __METHOD__);
            return false;
        }
    }
}